#!/bin/bash
BASH_PATH=$(cd `dirname $0`; pwd)
CURRENT_PATH=$(cd ${BASH_PATH}/../; pwd)
PASSWD="L74yjqvN"
DATE=$(date "+%Y-%m-%d %H:%M:%S") ####显示打印日志的时间
LOG_FILE=${CURRENT_PATH}/log/docker_init_$(date "+%Y%m%d%H%M%S").log
CONFIG_PATH=$(cd ${BASH_PATH}/../; pwd)
SHELL_PATH="/data/code/Shell/docker_service_init.sh"
# yaml文件位置
YAML_NAME="/data/code/Shell/config/docker_init.yaml"

function LOG() {
    USER=$(whoami) ####那个用户在操作
    if [ ! -e ${CURRENT_PATH}/log ];then
       mkdir ${CURRENT_PATH}/log
    fi
    if [ ! -f ${LOG_FILE} ];then
       touch ${LOG_FILE}
    fi
    echo "[${DATE}] ${USER} [$1] $2"
    echo "[${DATE}] ${USER} [$1] $2" >> ${LOG_FILE}  ######（$0脚本本身，$@将参数作为整体传输调用, >> 将输出结果以追加的方式添加重定向到本地文件中）
}

function Docker_Check_Status()
{
    RET=$(echo ${PASSWD} | sudo -S docker ps -a | grep "$1" | grep -v "Exited" | wc -l)
    if [ ${RET} -ne 0 ];then
        LOG "INFO" "$2 is running"
    else
        LOG "INFO" "$2 is not running"
        echo "${PASSWD}" | sudo docker start $1
        LOG "INFO" "$2 is starting"
        sleep 15s
    fi
    echo "${PASSWD}" | sudo -S docker exec $1 ${SHELL_PATH} $2
    LOG "INFO" "$2 service start success"
    return 0
}

function Start_Dokcer(){
    key
    flag=0
    # 逐行读取内容
    cat $1 | while read LINE
    do
        if [ $flag == 0 ];then
            # 属性开始标志 vehicle_type:
            if [ "$(echo $LINE | grep ":")" != "" ];then
                # 截取出key值
                key=$(echo "$LINE" | awk -F " " '{print $1}')
                value=$(echo "$LINE" | awk -F " " '{print $2}')
                Docker_Check_Status ${key%:} $value
                continue
            else
                # 如果关键词后面没有空格，则跳出继续查找
                continue
            fi
        fi
    done
}

function main()
{
    if [ $1 -eq 1 ];then
        LOG "INFO" "sleep Start"
        sleep 100s
        LOG "INFO" "sleep Finish, start docker service"
    fi

    # Start_Dokcer $YAML_NAME
    Docker_Check_Status a62e65b64e59 "centos_7.9.2009"
    Docker_Check_Status b04bcdaa0794 "Ubuntu_20_04"
    Docker_Check_Status 293ebf6e1ec6 "Ubuntu-desktop-lxde-vnc"
    ## Docker_Check_Status bbce55bb4609 "thinktan-brpc"
    ## Docker_Check_Status 6181e40c93b2 "sonarqube:latest"

    # 自动更新代码操作
    bash $BASH_PATH/git_update/git_update.sh 

    # 触发银星服务python脚本内容
    cd /volume1/web/Web/Silver_Star/service
    pid=$(ps aux | grep "server.py" | grep -v grep | wc -l)
    if [ $pid -ne 0 ];then
        LOG INFO  "Silver_Star service is running"
    else
        python3 server.py
        LOG INFO  "Silver_Star service start"
    fi  
    cd -

    # 删除多余文件
    if [ -e nohup.out ];then
        rm -rf nohup.out
    fi
    return 0
}
main